import { defineStore } from 'pinia';
import axios from '../utils/axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    isLoggedIn: false,
    token: localStorage.getItem('token') || null
  }),

  getters: {
    currentUser: (state) => state.user,
    isAuthenticated: (state) => state.isLoggedIn
  },

  actions: {
    async login(username, password) {
      try {
        const response = await axios.post('/auth/login', {
          username,
          password
        });

        // 在实际项目中，这里应该存储JWT令牌
        this.token = 'dummy-token'; // 占位符
        this.isLoggedIn = true;
        this.user = { username };

        localStorage.setItem('token', this.token);
        return response;
      } catch (error) {
        console.error('Login failed:', error);
        throw error;
      }
    },

    async register(username, email, password) {
      try {
        const response = await axios.post('/auth/register', {
          username,
          email,
          password
        });
        return response;
      } catch (error) {
        console.error('Registration failed:', error);
        throw error;
      }
    },

    logout() {
      this.user = null;
      this.isLoggedIn = false;
      this.token = null;
      localStorage.removeItem('token');
    },

    async fetchUserInfo() {
      if (!this.token) return;

      try {
        // 在实际项目中，这里应该发送请求获取用户信息
        // const response = await axios.get('/user/me');
        // this.user = response.data;
        this.isLoggedIn = true;
      } catch (error) {
        console.error('Failed to fetch user info:', error);
        this.logout();
      }
    }
  }
});